package com.atfzr.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * @author 望夜
 * @date 2023/8/21---10:02
 * @SuppressWarnings({"all"})
 *  1. 中断标志位，默认false
 *  2. t2 ---> t1发出了中断协商，t2调用t1.interrupt(),中断标志位为true
 *  3. 中断标志位为true，正常情况, 程序停止
 *  4. 中断标志位为true，异常情况，InterruptedException
 */
public class InterruptDemo3 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t 中断标志位：" + Thread.currentThread().isInterrupted()  + "程序停止");
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // 为什么要在异常出，再调用一次
                    e.printStackTrace();
                }
                System.out.println("t1  -----hello InterruptDemo3");
            }
        }, "t1");
        t1.start();

        System.out.println("------t1的默认中断标志位: " + t1.isInterrupted());

        try {
            //暂停毫秒
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            t1.interrupt(); //发出中断协商申请
        },"t2").start();
    }
}
